package com.nursinghome.admin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nursinghome.admin.service.AccountService;
import com.nursinghome.admin.service.ElderlyService;
import com.nursinghome.bean.Account;
import com.nursinghome.bean.RespBean;
import com.nursinghome.exception.NurisingHomeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/account")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private ElderlyService elderlyService;
    //根据日期查询账单
    @GetMapping
    public RespBean selectByadata(Integer pageNum,String data){
        if (data.length()>0 && data!=null){
            ZonedDateTime zdt = ZonedDateTime.parse(data);
            // 加上八小时
            ZonedDateTime newZdt = zdt.plusHours(8);
            // 转换为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
            data = newZdt.format(formatter);
        }
        PageHelper.startPage(pageNum, 5);
        List<Account> list = accountService.selectByadata(data);
        PageInfo<Account> pageInfo = new PageInfo<>(list);
        return RespBean.ok("",pageInfo);
    };
    //新增老人的账单
    @PostMapping
    public RespBean insert(@RequestBody @Validated Account account) throws NurisingHomeException{
        if (accountService.insert(account)) {
            return RespBean.ok("新增成功");
        }
        return RespBean.error("新增失败");
    };
    //todo
    //支付老人的账单
    @PutMapping
    public RespBean updata(@RequestBody  Account account) throws NurisingHomeException{
        if (accountService.updata(account)) {
            return RespBean.ok("支付成功");
        }
        return RespBean.error("支付失败");
    };
    //根据账单id回显数据
    @GetMapping("/byaid")
    public RespBean selectByAid(Long aid){
        return RespBean.ok("",accountService.selectByAid(aid));
    };
    //查询所有的老人
    @GetMapping("/allElderly")
    public RespBean allElderly(String data){
        List<HashMap<String, Object>> list = accountService.allElderly()
                .stream()
                .filter(elderly ->
                        accountService.selectByEname(data, elderly.getEid())
                ).map(elderly -> {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("key", elderly.getEid());
                    map.put("value", elderly.getEname() + elderly.getEusername());
                    return map;
                }).collect(Collectors.toList());
        list.forEach(System.out::println);
        return RespBean.ok("",list);
    }
}
